<?php
	
	/**
	 * get all companies
	 */
	$app->get('/company', authorize('user'), function () use ($app, $db) {
		$companies = array();
		$rs = $db->Company();
		foreach ( $rs as $company)
		{
			$companies[] = array (
				"id" => $company["id"],
				"name" => $company["name"],
				"ownerId" => $company["ownerId"]
			);
		}
		
		$app->response()->header("Content-Type", "application/json");
		echo json_encode( $companies );
	});
	
	/**
	 * get company by id
	 */
	$app->get('/company/:id', authorize('user'), function ($id) use ($app, $db) {
		$company = $db->Company()->where("id", $id)->fetch();
		$company = array (
			"id" => $company["id"],
			"name" => $company["name"],
			"ownerId" => $company["ownerId"]
		);
		
		$app->response()->header("Content-Type", "application/json");
		echo json_encode($company);
	});
	
	
	/**
	 * create company
	 */
	$app->post('/company', authorize('user'), function () use ($app, $db) {
		$company = json_decode( $app->request()->getBody(), true );
		$company = $db->Company()->insert($company);
		$company = array (
			"id" => $company["id"],
			"name" => $company["name"],
			"ownerId" => $company["ownerId"]
		);
		
		$app->response()->header("Content-Type", "application/json");
		echo json_encode($company);
	});
	
	
	/**
	 * update company
	 */
	$app->put('/company/:id', authorize('user'), function ($id) use ($app, $db) {
		$company = json_decode( $app->request()->getBody(), true );
		$db->Company("id",$id)->update($company);
		$company = array (
			"id" => $company["id"],
			"name" => $company["name"],
			"ownerId" => $company["ownerId"]
		);
		
		$app->response()->header("Content-Type", "application/json");
		echo json_encode($company);
	});
	
	
	/**
	 * delete company
	 */
	$app->delete('/company/:id', authorize('user'), function ($id) use ($app, $db) {
		$response = $db->Company("id",$id)->delete();
		
		$app->response()->header("Content-Type", "application/json");
		echo json_encode($response);
	});
		
?>